import { Injectable, NestInterceptor, CallHandler, ExecutionContext, HttpStatus } from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

interface ResponseData<T> {
  code: number;
  message: string;
  data: T | null;
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, ResponseData<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<ResponseData<T>> {
    return next.handle().pipe(
      map(data => {
        // 如果是 HttpException，不做处理，让异常过滤器来处理
        if (data instanceof Error) {
          throw data;
        }
        // 处理成功的响应
        return {
          code: HttpStatus.OK,
          message: '请求成功',
          data: data || null,
        };
      }),
    );
  }
}
